import axios from 'axios';
// import website from '@/config/website';
import {
    Dialog,
    Toast
} from 'vant';
import router from '@/router';
import {
    Base64
} from 'js-base64';



let baseURL = process.env.NODE_ENV === 'development' ? '/api' : ''
let customBase = 'http://www.tiaopiwu.com/'
// let customBase = 'http://api.tiaopiwu.com/'
const instance = axios.create({
    timeout: 30000,
    baseURL: customBase,
    // baseURL: 'http://39.107.244.200:60018',
    // baseURL: process.env.NODE_ENV === 'development' ? '/api' : ''
});

const serialize = data => {
    let list = [];
    Object.keys(data).forEach(ele => {
        list.push(`${ele}=${data[ele]}`)
    })
    return list.join('&');
};

instance.interceptors.request.use(config => {
        const meta = (config.meta || {});
        // const isToken = meta.isToken === false;

        config.headers['Token'] = window.localStorage.getItem('token')

        // if (!isToken && !config.headers['Blade-Auth']) {
        //     config.headers['Blade-Auth'] = `bearer ${window.localStorage.getItem('Authorization') || ''}`
        //     // 让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
        // }
        //headers中配置serialize为true开启序列化
        // if (config.method === 'post' && meta.isSerialize === true) {
        //     config.data = serialize(config.data);
        // }
        // if (config.method === 'post') {
        //     config.headers['Content-Type'] = 'application/json'
        //     config.data = JSON.stringify(config.data)
        // }
        config = proxy(config)

        return config
    },
    err => Promise.reject(err)
);

let is_pro = true
const BASE_URL = is_pro ? 'http://api.tiaopiwu.com' : customBase

const proxy = (config) => {
    const router = {
        // 'zrq-api': (BASE_URL ? BASE_URL : 'http://192.168.0.119:60018'),
        'api': (BASE_URL ? BASE_URL : 'http://192.168.0.119:60018'),
    }
    for (const route in router) {
        if (config.url.indexOf(route) >= 0) {
            config.url = config.url.replace('/' + route, '').replace(route, '')
            config.baseURL = router[route];
            break
        }
    }
    return config
}

instance.interceptors.response.use(
    res => {
        const resCode = res.status == 200 && (res.data.code || res.data.error_code) ? (res.data.code || res.data.error_code) : res.status
        if (resCode != 200) {
            switch (resCode) {
                case 422: {
                    const flag = Array.isArray(res.data.data) && res.data.data.length;
                    Dialog.alert({
                        message: flag ? res.data.data[0].message : res.data.msg
                    });
                    break;
                }
                case 401:
                    Dialog.alert({
                        message: res.data.msg,
                    }).then(() => {
                        router.push({
                            path: '/login'
                        })
                    });
                    break;
                case 400:
                    Toast(res.data.msg || res.data.error_description);
                    break;
                case 404:
                    break;
                default:
                    break;
            }
            return Promise.reject(res);
        }

        return res.data;
    },
    error => {
        Dialog.alert({
            title: '警告',
            message: error.message
        });
        return Promise.reject(error);
    }
);

const post = (url, data, config = {}) => instance.post(url, data, config);

const put = (url, data, config = {}) => instance.put(url, data, config);

const get = (url, params, config = {}) =>
    instance.get(url, {
        params,
        ...config
    });

const deleteMethod = (url, config = {}) => instance({
    url,
    method: 'delete',
    ...config
});
export default {
    req: instance,
    install(Vue) {
        Vue.prototype.$reqGet = get;
        Vue.prototype.$reqPost = post;
        Vue.prototype.$reqPut = put;
        Vue.prototype.$reqDel = deleteMethod;
        Vue.prototype.$req = instance;
    }
};